import json

import time
from django.http import HttpResponse, HttpRequest, HttpResponseRedirect
from django.urls import reverse

from WebSite.views.auth import Auth


def GetJsonResponse(dict_object, status=200):
	return HttpResponse(json.dumps(dict_object, ensure_ascii=False).encode("utf-8"), charset="utf-8", status=status)


# 未认证用户的普通页面，公共部分
def render_anonymous_page(func):
	def wrapper(request, *args, **kwargs):
		# 如果是认证用户
		if Auth.Is_Authenticated(request):
			# 转换成list传回前端
			context = {'username': request.session.get(Auth.SESSION_KEY_USER_NAME, '匿名用户'),
			           'timestamp': int(time.time())}

			return func(request, context, *args, **kwargs)

		else:
			context = {'username': None,
			           'timestamp': int(time.time())}
			return func(request, context, *args, **kwargs)

	return wrapper


def auth_required(func):
	def wrapper(request, *args, **kwargs):
		assert isinstance(request, HttpRequest)
		if Auth.Is_Authenticated(request):
			Auth.relogin(request)
			context = {'username': request.session.get(Auth.SESSION_KEY_USER_NAME, '匿名用户'),
			           'timestamp': int(time.time())}
		else:
			return HttpResponseRedirect(reverse('login'))

		return func(request, context, *args, **kwargs)

	return wrapper


def render_base(func):
	@auth_required
	def wrapper(request, *args, **kwargs):
		# 转换成list传回前端
		context = {'username': request.session.get(Auth.SESSION_KEY_USER_NAME, '匿名用户'),
		           'timestamp': int(time.time())}

		return func(request, context, *args, **kwargs)

	return wrapper


def required_json(func):
	def wrapper(request, *args, **kwargs):
		return func(request, *args, **kwargs)

	return wrapper
